package cn.icatw.wallpaperapi.controller;

import cn.icatw.wallpaperapi.common.Const;
import cn.icatw.wallpaperapi.common.R;
import cn.icatw.wallpaperapi.common.ResultStatusEnum;
import cn.icatw.wallpaperapi.domain.User;
import cn.icatw.wallpaperapi.domain.vo.LoginVo;
import cn.icatw.wallpaperapi.domain.vo.PassVo;
import cn.icatw.wallpaperapi.service.UserService;
import cn.icatw.wallpaperapi.utils.JwtUtil;
import cn.icatw.wallpaperapi.utils.MD5Util;
import cn.icatw.wallpaperapi.utils.NickNameUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;

/**
 * @author icatw
 * @date 2022/10/16
 * @email 762188827@qq.com
 * @apiNote
 */
@RestController
@Api(tags = "前台用户接口")
@RequestMapping("/api/user")
public class FrontUserController {
    @Resource
    private UserService userService;
    @Resource
    JwtUtil jwtUtil;

    //TODO 登陆注册，个人信息获取及修改，修改密码
    @PostMapping("/login")
    @ApiOperation("登陆")
    public R login(@RequestBody @NotNull LoginVo loginVo) {
        String account = loginVo.getAccount();
        User user = userService.getOne(new QueryWrapper<User>().eq("account", account));
        if (user != null) {
            Integer status = user.getStatus();
            if (status == 0) {
                return R.fail(ResultStatusEnum.USER_NOT_ALLOWED.getCode(), ResultStatusEnum.USER_NOT_ALLOWED.getMessage());
            }
            String md5 = MD5Util.string2MD5(loginVo.getPassword());

            if (md5.equals(user.getPassword())) {
                //    账号密码正确，生成token返回，更新登陆时间
                user.setLastLoginTime(new Date());
                userService.updateById(user);
                String token = jwtUtil.generateToken(String.valueOf(user.getId()));
                return R.ok(token);
            }
            return R.fail(ResultStatusEnum.PASSWORD_NOT_MATCHING.getCode()
                    , ResultStatusEnum.PASSWORD_NOT_MATCHING.getMessage());
        }
        return R.fail(ResultStatusEnum.PASSWORD_NOT_MATCHING.getCode()
                , ResultStatusEnum.PASSWORD_NOT_MATCHING.getMessage());
    }

    @PostMapping("/register")
    @ApiOperation("注册")
    public R register(@RequestBody @NotNull User user) {
        //    注册。先判断账号是否存在
        long account = userService.count(new QueryWrapper<User>().eq("account", user.getAccount()));
        if (account > 0) {
            return R.fail(ResultStatusEnum.USER_EXISTS.getCode(), ResultStatusEnum.USER_EXISTS.getMessage());
        }
        String md5Password = MD5Util.string2MD5(user.getPassword());
        user.setPassword(md5Password);
        user.setStatus(1);
        //默认随机昵称
        user.setNickname(NickNameUtil.getStringRandom(5));
        //性别为2为未知0女 1男
        user.setSex(2);
        user.setAvatar(Const.INITIAL_AVATAR);
        user.setSign(Const.INITIAL_SIGN);
        return R.ok(this.userService.save(user));
    }

    @GetMapping("/getCurrentUserInfo")
    @ApiOperation("获取当前登陆用户信息")
    public R getCurrentUserInfo(HttpServletRequest request) {
        String userId = jwtUtil.getClaimByToken(request);
        return R.ok(userService.getById(userId));
    }

    @PostMapping("/updateUserAvatar")
    @ApiOperation("修改用户头像")
    public R updateAvatar(String url, HttpServletRequest request) {
        String userId = jwtUtil.getClaimByToken(request);
        if (StringUtils.isEmpty(url) || StringUtils.isEmpty(userId)) {
            return R.fail();
        }
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(User::getId, userId)
                .set(User::getAvatar, url);
        userService.update(lambdaUpdateWrapper);
        return R.ok();
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation("修改用户信息")
    public R update(@RequestBody @NotNull User user) {
        return R.ok(userService.updateById(user));
    }

    @PostMapping("/updateUserPass")
    @ApiOperation("修改用户密码")
    public R updatePass(@RequestBody @NotNull PassVo passVo, HttpServletRequest request) {
        if (passVo == null) {
            return R.fail("密码不能为空！");
        }
        String oldPassword = passVo.getOldPassword();
        String newPassword = passVo.getNewPassword();
        String confirmPassword = passVo.getConfirmPassword();
        if (oldPassword != null && newPassword != null && confirmPassword != null) {
            String userId = jwtUtil.getClaimByToken(request);
            User user = userService.getById(userId);
            //旧密码加密与数据库md5密码进行比较
            String md5 = MD5Util.string2MD5(oldPassword);
            if (md5.equals(user.getPassword())) {
                //    密码不相等
                if (!newPassword.equals(confirmPassword)) {
                    return R.fail("新密码和确认密码不一致！");
                }
                user.setPassword(MD5Util.string2MD5(confirmPassword));
                return R.ok(userService.updateById(user));
            }
        }
        return R.fail();
    }
}
